package com.atguigu.tingshu.account.receiver;

import com.atguigu.tingshu.account.service.UserAccountService;
import com.atguigu.tingshu.common.login.TsLogin;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.rabbitmq.client.Channel;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;


@Slf4j
@Component
public class AccountReceiver {

    @Autowired
    private UserAccountService userAccountService;


    /**
     * 用户注册成功，发送消息给账户模块，用户id
     * @param userId
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_USER_REGISTER),
            exchange = @Exchange(value = MqConst.EXCHANGE_USER),
            key = MqConst.ROUTING_USER_REGISTER
    ))
    public void register(Long userId, Message message, Channel channel){
        //  判断当前用户Id
        if (null != userId){
            System.out.println("用户注册成功，发送消息给账户模块，用户id："+userId);
            //  调用服务层方法.
            userAccountService.initUserAccount(userId);
            //  如果业务处理失败！重试！借助redis 来记录重试的次数！count+1 +1 +1;
            //  直接记录消息异常记录表；发送短信--人工处理！
        }
        //  签收消息！
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }

    /**
     * 监听支付成功
     * @param orderNo
     * @param message
     * @param channel
     */
    @SneakyThrows
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = MqConst.QUEUE_RECHARGE_PAY_SUCCESS),
            exchange = @Exchange(value = MqConst.EXCHANGE_ORDER),
            key = MqConst.ROUTING_RECHARGE_PAY_SUCCESS
    ))
    public void rechargePaySuccess(String orderNo, Message message, Channel channel) {
        try {
            //  判断
            if (!StringUtils.isEmpty(orderNo)) {
                //  调用方法
                userAccountService.rechargePaySuccess(orderNo);
            }
        } catch (Exception e) {
            e.getMessage();
        }
        //  手动确认消息.
        channel.basicAck(message.getMessageProperties().getDeliveryTag(),false);
    }
}
